package xj.graph2d.tools;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.util.Observer;

import xj.graph2d.DrawShape;
import xj.graph2d.DrawShapeConstants;
import xj.graph2d.DrawShapeSearch;

/**
 * For selecting multiple shapes
 */
public class SelectionTool extends SimpleDrawTool {

  public SelectionTool() {
  }

  @Override
  public void mouseLButtonPressed(Observer observer, Point p, int modifiers) {

    if (debug) {
      System.out.println("SelectionTool.mouseLButtonPressed()");
    }

    start(observer);
    if (view != null) {
      Graphics2D g2 = canvas.getGraphics2D();
      canvas.setRenderingHints(g2);
      canvas.setTransform(g2);

      if ((modifiers & InputEvent.SHIFT_DOWN_MASK) != 0) {

	DrawShape prevSelectedShape = doc.getSelectedShape();
	if (prevSelectedShape != null) {
	  doc.setSelectedShape(null);
	  canvas.repaintShape(prevSelectedShape, true);
	}

	prev = view.physicalToVirtual(p);

	DrawShapeSearch.Result result = doc.search(prev);
	if (result != null
	    && result.position != DrawShapeConstants.PointOutside) {
	  if (debug) {
	    System.out
		.println("SelectionTool.mouseLButtonPressed(): find shape");
	  }

	  DrawShape shape = result.shape;
	  doc.flipSelection(shape);
	  canvas.repaintShape(shape, true);
	} else {
	  if (!doc.getSelectionSet().isEmpty()) {
	    // unselect all shapes
	    /*
	     * BitSet sel = doc.getSelectionSet(); for(int i =
	     * sel.nextSetBit(0); i >= 0; i = sel.nextSetBit(i+1)) {
	     * sel.clear(i); DrawShape s = doc.get(i);
	     * canvas.repaintShape(s, true); }
	     */
	    doc.clearSelectionSet();
	    canvas.repaint();
	    // doc.setSelectedShape(null);
	    doc.selectionSetUpdated();
	  }
	}
      } else if ((modifiers & InputEvent.CTRL_DOWN_MASK) != 0) {

      }
      g2.dispose();
    }
  }

  protected static final boolean debug = false;

}
